const express = require("express");
const router = express.Router();
const { college } = require("../../models/college");

// 获取所有学院
router.get('/', async(req, res) => {
    let { current, size } = req.query
    current = current ? current : 1
    size = size ? size : 5
    const total = await (new Promise((resolve, reject) => college.find().then(data => resolve(data.length))))
    college.find().skip((current - 1) * size).limit(Number(size)).then(result => {
        res.status(200).json({
            code: 200,
            data: {
                size,
                total,
                pages: Math.ceil(total / size),
                current,
                records: result.map(item => {
                    return {
                        id: item._id,
                        name: item.name,
                        createDate: item.createDate
                    }
                })
            }
        })
    })
})

// 添加学院
router.post('/', (req, res) => {
    college.findOne({ name: req.body.name }).then(result => {
        if (result) return res.json({
            code: 400,
            msg: '学院已存在'
        })
        new college({
            name: req.body.name
        }).save(() => {
            res.status(200).json({
                code: 200,
                msg: '添加成功'
            })
        })
    })
})

// 修改学院
router.put('/', (req, res) => {
    college.findOneAndUpdate({ _id: req.body.id }, { $set: { name: req.body.name } }, { new: true }).then(() => {
        res.status(200).json({
            code: 200,
            msg: '修改成功'
        })
    })
})

// 删除学院
router.delete('/:id', (req, res) => {
    college.findOneAndRemove({ _id: req.params.id }).then(() => {
        res.status(200).json({
            code: 200,
            msg: '删除成功'
        })
    })
})

module.exports = router;